package com.example.config;


import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.cors.CorsConfiguration;
import org.springframework.web.cors.UrlBasedCorsConfigurationSource;
import org.springframework.web.filter.CorsFilter;

/**
 * 跨域
 */
@Configuration
public class CorsConfig{

    @Bean
    public FilterRegistrationBean corsFilter(){
        UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource();
        CorsConfiguration config = new CorsConfiguration();

        //是否发送cookie
        config.setAllowCredentials(true);
        //允许的网站域名，全允许则设为*
        config.addAllowedOrigin("*");
        //允许HEADER或METHOD，*为全部
        config.addAllowedHeader("content-type");
        config.addAllowedHeader("anan-token");
        config.addAllowedMethod("*");
        source.registerCorsConfiguration("/**", config);
        FilterRegistrationBean bean=new FilterRegistrationBean(new CorsFilter(source));
        //这个顺序很重要，为避免麻烦请设置在最前
        bean.setOrder(0);
        System.out.println("通过跨域过滤器");
        return bean;
    }

}

